package com.woke.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnRefreshListener;
import com.bean.Banner;
import com.bean.TabColumn;
import com.example.woke.ChannelActivateActivity;
import com.example.woke.HtmlActivity;
import com.example.woke.LoadActivity;
import com.example.woke.MoneyonlineActivity;
import com.example.woke.ReciverFActivity;
import com.example.woke.ZhongcaiReciveActivity;
import com.example.woke1.CaixintongActivity;
import com.example.woke1.ZhcailicaiActivity;
import com.example.woke1.ZhongchouActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.http.HttpMethods;
import com.nova.lfh.zxing.RScannerActivity;
import com.rd.PageIndicatorView;
import com.woke.adapter.AdapterBannerPager;
import com.woke.adapter.OnItemClickListener;
import com.woke.adapter.TabHomeColumnViewProvider;
import com.woke.addressactivity.ExChangeActivity;
import com.woke.method.ImageHandler;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

import static me.drakeet.multitype.MultiTypeAsserts.assertAllRegistered;


/**
 * 首页
 */
public class TabHomeFragmentCopy extends BaseFrag  {

    private View rootView;
    private MultiTypeAdapter mMulitypeAdapter;
    private ViewPager mViewPager;
    private PageIndicatorView mPageIndicatorView;
    private ImageHandler mHandler;
    private AdapterBannerPager mBannerAdapter;
    private List<Banner> mBannerList = new ArrayList<>();
    private String[] mColumnTitles;

    private IRecyclerView iRecyclerView;

//    private NestedScrollView mNestedScrollView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_tab_home_copy, container, false);
//            mNestedScrollView =(NestedScrollView)rootView.findViewById(R.id.nestedScrollView_home);
//            initToolbar(rootView, false);
            inittoolbar(rootView);
            setTitle(getResources().getString(R.string.app_name));






            iRecyclerView = (IRecyclerView) rootView.findViewById(R.id.iRecyclerView);

            iRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));

            // an custom load more footer view, you can customize it yourself.
//            LoadMoreFooterView loadMoreFooterView = (LoadMoreFooterView) iRecyclerView.getLoadMoreFooterView();

            // you can also add header and footer like this
            // note: header and refresh header are different, footer and load more footer are different too.
            View headerView = inflater.inflate(R.layout.adapter_banner_viewpager, container, false);
            mViewPager = (ViewPager) headerView.findViewById(R.id.banner_viewpager);
            mPageIndicatorView = (PageIndicatorView) headerView.findViewById(R.id.banner_pageIndicator);

            getBannerList();
            iRecyclerView.addHeaderView(headerView);
            View footView = inflater.inflate(R.layout.item_test, container, false);
            getBannerList();
            iRecyclerView.addFooterView(footView);


            initMulitypeAdapter();

            iRecyclerView.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh() {
                    getBannerList();
                }
            });




        } else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

    private void getBannerList() {
        HttpMethods.getInstance().getBannerList(mBannersObserver,1);
    }

    private void inittoolbar(View rootView) {
        mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        mToolbarTitle = (TextView) rootView.findViewById(R.id.toolbar_title);
        if (mToolbar != null) {
            mToolbar.setTitle("");

            mToolbar.inflateMenu(getMenuId());
            //menu xml 使用actionLayout 自定义menu布局会导致setOnMenuItemClickListener事件失效
            MenuItem menuItem = mToolbar.getMenu().findItem(R.id.scan);
            menuItem.getActionView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转扫一扫
                    if (getActivity() != null) {
                        IntentIntegrator.forSupportFragment(TabHomeFragmentCopy.this).setCaptureActivity(RScannerActivity.class).initiateScan();
//                        new IntentIntegrator(getActivity()).setCaptureActivity(RScannerActivity.class).initiateScan();
                    }
                }
            });
            mToolbar.setNavigationIcon(null);

        }
    }

    ;

    @Override
    public void onResume() {
        super.onResume();
        if (mHandler != null) {
            mHandler.setIsPause(false);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mHandler != null) {
            mHandler.setIsPause(true);
        }
    }


    @Override
    public int getMenuId() {
        return R.menu.tabhome_scan;
    }

    @Override
    public void OnNavigationClickListener(View v) {

    }

    @Override
    public boolean OnMenuItemClickListener(MenuItem item) {
        return false;
    }



    private Observer<List<Banner>> mBannersObserver = new Observer<List<Banner>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<Banner> value) {
            if (value != null) {
                intViewPagerAndIndicator(value);
            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private void intViewPagerAndIndicator(List<Banner> list) {
        if (list != null && list.size() > 0) {
            mBannerList.clear();
            mBannerList.addAll(list);
        }
        if (mBannerAdapter == null) {
            mBannerAdapter = new AdapterBannerPager(mBannerList);
            mBannerAdapter.setOnItemClickListener(mItemClickListener);
            mViewPager.setAdapter(mBannerAdapter);
            mHandler = new ImageHandler(getContext());
        } else {
            mBannerAdapter.notifyDataSetChanged();
        }
        mPageIndicatorView.setCount(mBannerList.size());
        mPageIndicatorView.setViewPager(mViewPager);

        mHandler.setViewPage(mViewPager);
        mHandler.sendEmptyMessage(ImageHandler.MSG_UPDATE_IMAGER);
    }

    private void initMulitypeAdapter() {
        mColumnTitles = getResources().getStringArray(R.array.tabhome_column_content);
        String[] mColumnRemarkd = getResources().getStringArray(R.array.tabhome_column_content_remark);
        TypedArray typedArray = getResources().obtainTypedArray(R.array.tabhome_column_icon);
        if (mColumnTitles.length != typedArray.length()) {
            throw new RuntimeException("title length != icons length");
        }
        Items mItems = new Items();

        for (int i = 0; i < mColumnTitles.length; i++) {
            TabColumn column = new TabColumn(typedArray.getResourceId(i, R.mipmap.ic_tabhome_wallet), mColumnTitles[i], null);
            column.setRemark(mColumnRemarkd[i]);
            mItems.add(column);
        }
        typedArray.recycle();
//		BannerItems bannerItems = new BannerItems ();
//		List<Banner> banners = new ArrayList<> ();
//		for (int i = 0; i < 5; i++) {
//			banners.add (new Banner ());
//		}
//		bannerItems.setBanners (banners);
//		mItems.add (bannerItems);
//
        mMulitypeAdapter = new MultiTypeAdapter();
        mMulitypeAdapter.register(TabColumn.class, new TabHomeColumnViewProvider(mItemClickListener));
//
        iRecyclerView.setAdapter(mMulitypeAdapter);

        mMulitypeAdapter.setItems(mItems);
        mMulitypeAdapter.notifyDataSetChanged();
        if (mItems.size() > 0) {
            assertAllRegistered(mMulitypeAdapter, mItems);//执行这句话时,必须保证 Items.size()>0
        }
    }

    private OnItemClickListener mItemClickListener = new OnItemClickListener() {
        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (object instanceof TabColumn) {
                MyApp application = (MyApp) getActivity().getApplication();
                if (application.getDatas_load() == null) {
                    aralogid("还未登录", "前往登录", 1);
                    return;
                }
                TabColumn column = (TabColumn) object;
                Intent intent = new Intent();
                if (mColumnTitles[0].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财钱包
                        intent.setClass(getActivity(), ReciverFActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[1].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财车险
                        int userid = Integer.parseInt(application.getDatas_load().getId());
                        if (userid > 0) {
                            HttpMethods.getInstance().fetchDirectUrl(carInsuranceObserver, userid);
                        }

                    }
                } else if (mColumnTitles[2].equals(column.getColumnName())) {
                    //中交所
                    intent.setClass(getActivity(), ExChangeActivity.class);
                    startActivity(intent);
                } else if (mColumnTitles[3].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财理财
                        intent.setClass(getActivity(), ZhcailicaiActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[4].equals(column.getColumnName())) {
                    //万卡 更换为信用卡
                    intent.setClass(getActivity(), ExChangeActivity.class);
                    intent.putExtra("sort", 2);
                    startActivity(intent);
                } else if (mColumnTitles[5].equals(column.getColumnName())) {
                    //人品贷 更换为网贷
                    intent.setClass(getActivity(), ExChangeActivity.class);
                    intent.putExtra("sort", 1);
                    startActivity(intent);
                } else if (mColumnTitles[6].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财借贷
                        intent.setClass(getActivity(), MoneyonlineActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[7].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财众筹
                        intent.setClass(getActivity(), ZhongchouActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[8].equals(column.getColumnName())) {
                    //财富通
                    intent.setClass(getActivity(), CaixintongActivity.class);
                    startActivity(intent);
                }
            } else if (object instanceof Banner) {
                Banner banner = (Banner) object;
                if (getContext() != null) {
                    MyApp application = (MyApp) getActivity().getApplication();
                    int userid = 1;
                    if (null != application.getDatas_load()) {
                        userid = Integer.parseInt(application.getDatas_load().getId());
                    }
                    if (userid <= 0) {
                        userid = 1;
                    }
                    String encodeUserId = new String((Base64.encode(String.valueOf(userid).getBytes(), Base64.DEFAULT)));
                    Intent intent = new Intent(getContext(), HtmlActivity.class);
                    intent.putExtra("urlname", banner.getAd_name());
                    intent.putExtra("url", banner.getAd_url() + "/NOxBL7xp/" + encodeUserId);
                    getContext().startActivity(intent);
                }
            }
        }
    };
    AlertDialog alertDialog;

    private void aralogid(String info, String kll, final int ppp) {
        alertDialog = new AlertDialog.Builder(getActivity()).
                setTitle(info).
                setMessage(kll).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), LoadActivity.class);
                        startActivity(intent);
                        alertDialog.dismiss();
                    }
                }).
                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //接收扫码
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (getContext() == null) return;
            if (TextUtils.isEmpty(result.getContents())) {
            } else {
                String serialNum = getserialNumberFromUrl(result.getContents());
                if (!TextUtils.isEmpty(serialNum)) {
                    //商家激活码
                    MyApp application = (MyApp) getActivity().getApplication();

                    if (null != application.getDatas_load()) {
                        int userId = Integer.parseInt(application.getDatas_load().getId());
                        HttpMethods.getInstance()
                                .activateSeriesNo(mActivateObserver, userId, serialNum);
                    }

                } else {
                    String qrCode = result.getContents();
                    if (!TextUtils.isEmpty(qrCode)) {
                        if (qrCode.length() > 0) {

                            Intent intent = new Intent(getContext(), ZhongcaiReciveActivity.class);
                            intent.putExtra("result", result.getContents());
                            startActivity(intent);
                            Toast.makeText(getContext(), result.getContents(), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                }
            }
        } else {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 截取链接上的 的serialNumber值
     * &serialNumber=42b26142ca6f180d
     *
     * @param urlStr
     * @return
     */
    private String getserialNumberFromUrl(String urlStr) {
        Pattern p = Pattern.compile("&serialNumber=[A-Za-z0-9]+");
        Matcher m = p.matcher(urlStr);
        if (m.find()) {
            String[] split = m.group().split("=");
            return split[1];
        }
        return "";
    }

    private Observer<String> mActivateObserver = new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String serialNum) {
            if (!TextUtils.isEmpty(serialNum)) {
                if (getContext() != null) {
                    MyApp application = (MyApp) getActivity().getApplication();

                    if (null != application.getDatas_load()) {
                        int userId = Integer.parseInt(application.getDatas_load().getId());

                        if (userId > 0) {
                            Intent sk = new Intent(getContext(), ChannelActivateActivity.class);
                            sk.putExtra("serialNum", serialNum);
                            sk.putExtra("userId", userId);
                            startActivity(sk);
                        }
                    }

                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                Log.e("----", "" + e.getMessage());
                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onComplete() {

        }
    };

    private Observer<String> carInsuranceObserver = new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String value) {
            if (!TextUtils.isEmpty(value)) {
                if (getContext() != null) {
                    Intent intent = new Intent(getContext(), HtmlActivity.class);
                    intent.putExtra("urlname", "众安车险");
                    intent.putExtra("url", value);
                    getContext().startActivity(intent);

                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onComplete() {

        }
    };
}
